package com.marklogic.ps.servicetester.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XmlUtil {

	public static String formatXml(String source) {
		StringWriter xmlString = new StringWriter();
		try {
			formatXml(source, xmlString);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			try {
				formatXml("<results warning='more than one node'>" + source + "</results>", xmlString);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (JDOMException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return xmlString.toString();
	}
	
	private static void formatXml(String source, StringWriter xmlString) throws IOException, JDOMException {
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(new StringReader(source));
		XMLOutputter XMLoutput = new XMLOutputter(Format.getPrettyFormat());
		XMLoutput.output(doc, xmlString);
	}

}
